import { Context } from 'koa';
import { AppContext, UserType, UserStatus } from '@/types';
import UserService from '@/services/UserService';
import AuthService from '@/services/AuthService';
import { validate, commonSchemas } from '@/utils/validator';
import * as response from '@/utils/response';
import Joi from 'joi';
import logger from '@/utils/logger';

/**
 * 用户控制器
 */
export class UserController {
  /**
   * 创建用户
   */
  async create(ctx: Context) {
    const appCtx = ctx as AppContext;

    const schema = Joi.object({
      email: commonSchemas.email.required(),
      password: commonSchemas.password.required(),
      firstName: Joi.string().max(100),
      lastName: Joi.string().max(100),
      type: Joi.string().valid(...Object.values(UserType)),
      roleId: commonSchemas.uuid,
      tenantId: commonSchemas.uuid,
    });

    interface CreateUserData {
      email: string;
      password: string;
      firstName?: string;
      lastName?: string;
      type?: string;
      roleId?: string;
      tenantId?: string;
    }

    const data = await validate<CreateUserData>(ctx.request.body as any, schema);

    // 如果不是超级管理员，使用当前租户ID
    if (appCtx.state.user?.type !== UserType.SUPER_ADMIN) {
      data.tenantId = appCtx.state.tenant?.id || appCtx.state.user?.tenantId || undefined;
    }

    const user = await UserService.createUser(data as any, appCtx.state.user?.id);

    response.created(ctx, user.toSafeObject(), '用户创建成功');
  }

  /**
   * 获取用户详情
   */
  async getById(ctx: Context) {
    const { id } = ctx.params;

    const user = await UserService.getUserById(id);

    if (!user) {
      return response.notFound(ctx, '用户不存在');
    }

    response.success(ctx, user.toSafeObject());
  }

  /**
   * 获取用户列表
   */
  async list(ctx: Context) {
    const appCtx = ctx as AppContext;

    const schema = Joi.object({
      page: Joi.number().integer().min(1).default(1),
      pageSize: Joi.number().integer().min(1).max(100).default(20),
      type: Joi.string().valid(...Object.values(UserType)),
      status: Joi.string().valid(...Object.values(UserStatus)),
      search: Joi.string().max(255),
      tenantId: commonSchemas.uuid,
    });

    interface ListUsersFilter {
      page: number;
      pageSize: number;
      type?: string;
      status?: string;
      search?: string;
      tenantId?: string;
    }

    const filter = await validate<ListUsersFilter>(ctx.query as any, schema);

    // 如果不是超级管理员，过滤当前租户用户
    if (appCtx.state.user?.type !== UserType.SUPER_ADMIN) {
      filter.tenantId = appCtx.state.tenant?.id || appCtx.state.user?.tenantId || undefined;
    }

    const result = await UserService.listUsers(filter as any);

    response.paginated(
      ctx,
      result.data,
      result.pagination.total,
      result.pagination.page,
      result.pagination.pageSize,
    );
  }

  /**
   * 更新用户
   */
  async update(ctx: Context) {
    const appCtx = ctx as AppContext;
    const { id } = ctx.params;

    const schema = Joi.object({
      email: commonSchemas.email,
      firstName: Joi.string().allow('').max(100),
      lastName: Joi.string().allow('').max(100),
      roleId: commonSchemas.uuid,
      status: Joi.string().valid(...Object.values(UserStatus)),
      avatar: Joi.string().uri().allow(''),
    });

    interface UpdateUserData {
      email?: string;
      firstName?: string;
      lastName?: string;
      roleId?: string;
      status?: string;
      avatar?: string;
    }

    const data = await validate<UpdateUserData>(ctx.request.body as any, schema);

    const user = await UserService.updateUser(id, data as any, appCtx.state.user?.id);

    response.success(ctx, user.toSafeObject(), '用户更新成功');
  }

  /**
   * 激活用户
   */
  async activate(ctx: Context) {
    const appCtx = ctx as AppContext;
    const { id } = ctx.params;

    const user = await UserService.activateUser(id, appCtx.state.user?.id);

    response.success(ctx, user.toSafeObject(), '用户已激活');
  }

  /**
   * 禁用用户
   */
  async deactivate(ctx: Context) {
    const appCtx = ctx as AppContext;
    const { id } = ctx.params;

    const user = await UserService.deactivateUser(id, appCtx.state.user?.id);

    response.success(ctx, user.toSafeObject(), '用户已禁用');
  }

  /**
   * 删除用户
   */
  async delete(ctx: Context) {
    const appCtx = ctx as AppContext;
    const { id } = ctx.params;

    await UserService.deleteUser(id, appCtx.state.user?.id);

    response.success(ctx, null, '用户删除成功');
  }

  /**
   * 批量删除用户
   */
  async batchDelete(ctx: Context) {
    const appCtx = ctx as AppContext;
    
    const schema = Joi.object({
      ids: Joi.array().items(commonSchemas.uuid).min(1).max(100).required(),
    });

    const data = await validate<{ ids: string[] }>(ctx.request.body as any, schema);

    const results = {
      success: 0,
      failed: 0,
    };

    for (const id of data.ids) {
      try {
        await UserService.deleteUser(id, appCtx.state.user?.id);
        results.success++;
      } catch (error) {
        results.failed++;
        logger.error(`Failed to delete user ${id}:`, error);
      }
    }

    response.success(
      ctx, 
      results, 
      `批量删除完成：成功 ${results.success} 个，失败 ${results.failed} 个`
    );
  }

  /**
   * 重置用户密码
   */
  async resetPassword(ctx: Context) {
    const { id } = ctx.params;

    const schema = Joi.object({
      newPassword: commonSchemas.password.required(),
    });

    const data = await validate<{ newPassword: string }>(ctx.request.body as any, schema);

    await AuthService.resetPassword(id, data.newPassword);

    response.success(ctx, null, '密码重置成功');
  }

  /**
   * 分配角色
   */
  async assignRole(ctx: Context) {
    const appCtx = ctx as AppContext;
    const { id } = ctx.params;

    const schema = Joi.object({
      roleId: commonSchemas.uuid.required(),
    });

    const data = await validate<{ roleId: string }>(ctx.request.body as any, schema);

    const user = await UserService.assignRole(
      id,
      data.roleId,
      appCtx.state.user?.id,
    );

    response.success(ctx, user.toSafeObject(), '角色分配成功');
  }

  /**
   * 批量导入用户
   */
  async batchImport(ctx: Context) {
    const appCtx = ctx as AppContext;
    const { user: currentUser, tenant } = appCtx.state;

    const schema = Joi.object({
      users: Joi.array().items(
        Joi.object({
          email: commonSchemas.email.required(),
          password: Joi.string().min(6),
          firstName: Joi.string().max(100),
          lastName: Joi.string().max(100),
          status: Joi.string().valid('active', 'inactive'),
          roleId: commonSchemas.uuid,
          departmentId: commonSchemas.uuid,
        })
      ).min(1).max(1000).required(),
    });

    const data = await validate<{ users: any[] }>(ctx.request.body as any, schema);

    const results = {
      success: [] as any[],
      failed: [] as any[],
    };

    // 批量处理用户导入
    for (const userData of data.users) {
      try {
        // 设置默认密码（如果未提供）
        if (!userData.password) {
          // 优先使用租户的默认密码，否则使用系统默认密码
          userData.password = tenant?.defaultPassword || 'Pass123456';
        }

        // 设置默认状态
        if (!userData.status) {
          userData.status = 'active';
        }

        // 如果不是超级管理员，使用当前租户ID
        if (currentUser?.type !== UserType.SUPER_ADMIN) {
          userData.tenantId = tenant?.id || currentUser?.tenantId;
        }

        // 创建用户
        await UserService.createUser(userData as any, currentUser?.id);
        results.success.push({
          email: userData.email,
          name: `${userData.firstName || ''} ${userData.lastName || ''}`.trim(),
        });
      } catch (error: any) {
        results.failed.push({
          email: userData.email,
          error: error.message || '导入失败',
        });
      }
    }

    logger.info(
      `批量导入用户：成功 ${results.success.length} 个，失败 ${results.failed.length} 个 by ${currentUser?.email}`
    );

    response.success(ctx, results, '批量导入完成');
  }

  /**
   * 获取用户导出数据
   */
  async getExportData(ctx: Context) {
    const appCtx = ctx as AppContext;

    // 获取查询参数
    const schema = Joi.object({
      type: Joi.string().valid(...Object.values(UserType)),
      status: Joi.string().valid(...Object.values(UserStatus)),
      search: Joi.string().max(255),
      tenantId: commonSchemas.uuid,
    });

    const filter = await validate<any>(ctx.query as any, schema);

    // 如果不是超级管理员，过滤当前租户用户
    if (appCtx.state.user?.type !== UserType.SUPER_ADMIN) {
      filter.tenantId = appCtx.state.tenant?.id || appCtx.state.user?.tenantId;
    }

    // 获取所有数据（不分页）
    const result = await UserService.listUsers({
      ...filter,
      page: 1,
      pageSize: 10000, // 导出最多10000条
    });

    // 转换数据格式
    const exportData = result.data.map((user: any) => ({
      邮箱: user.email,
      名字: user.firstName || '',
      姓氏: user.lastName || '',
      姓名: `${user.firstName || ''} ${user.lastName || ''}`.trim(),
      角色: user.role?.name || '',
      部门: user.department?.name || '',
      状态: user.status === 'active' ? '启用' : '禁用',
      最后登录IP: user.lastLoginIp || '',
      最后登录时间: user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString('zh-CN') : '',
      创建时间: new Date(user.createdAt).toLocaleString('zh-CN'),
    }));

    response.success(ctx, exportData);
  }

  /**
   * 获取导入模板数据
   */
  async getImportTemplate(ctx: Context) {
    // 返回模板列配置和示例数据
    const templateConfig = {
      columns: [
        { header: '邮箱', key: 'email', width: 25 },
        { header: '密码', key: 'password', width: 20 },
        { header: '名字', key: 'firstName', width: 15 },
        { header: '姓氏', key: 'lastName', width: 15 },
        { header: '角色ID', key: 'roleId', width: 36 },
        { header: '部门ID', key: 'departmentId', width: 36 },
        { header: '状态', key: 'status', width: 10 },
      ],
      sampleData: [
        {
          email: 'zhangsan@example.com',
          password: 'Pass123456',
          firstName: '三',
          lastName: '张',
          roleId: '留空或填写角色ID',
          departmentId: '留空或填写部门ID',
          status: 'active',
        },
        {
          email: 'lisi@example.com',
          password: '留空则使用租户默认密码',
          firstName: '四',
          lastName: '李',
          roleId: '',
          departmentId: '',
          status: 'inactive',
        },
      ],
    };

    response.success(ctx, templateConfig);
  }
}

export default new UserController();

